import React from 'react';

export default class App extends React.Component {
  state = {
    todoText: '',
    todoData: []
  };

  componentDidMount() {
    setTimeout(() => {
      this.refs.titleRef.innerText = '待办事项列表';
    }, 1000);
  }

  setTodoText(text) {
    this.setState({
      todoText: text
    });
  }

  addTodo() {
    if (!this.state.todoText.length) return;
    this.setState({
      todoData: [
        ...this.state.todoData,
        {
          id: new Date().getTime(),
          content: this.state.todoText,
          completed: false
        }
      ],
      todoText: ''
    });
  }

  toggleTodo(id) {
    this.setState({
      todoData: this.state.todoData.map((todo) => {
        if (todo.id === id) {
          todo.completed = !todo.completed;
        }
        return todo;
      })
    });
  }

  removeTodo(id) {
    this.setState({
      todoData: this.state.todoData.filter((todo) => todo.id !== id)
    });
  }

  render() {
    const { todoText, todoData } = this.state;
    return (
      <div>
        <div>
          <h1 ref="titleRef">TodoList</h1>
          <input
            type="text"
            placeholder="Input some..."
            value={todoText}
            onInput={(e) => this.setTodoText(e.target.value)}
          />
          <button onClick={() => this.addTodo()}>Add</button>
        </div>
        <div>
          <ul>
            {todoData.map((todo) => (
              <li key={todo.id}>
                <input
                  type="checkbox"
                  checked={todo.completed}
                  onClick={() => this.toggleTodo(todo.id)}
                />
                <span className={todo.completed ? 'completed' : ''}>
                  {todo.content}
                </span>
                <button onClick={() => this.removeTodo(todo.id)}>Delete</button>
              </li>
            ))}
          </ul>
        </div>
      </div>
    );
  }
}
